<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="elibrary.*"%>
<%@ page language="java" import="java.util.*"%>
<%@ include file="config.jsp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>My-Library | Make Reservation</title>
    </head>
    <body>
        <%
            try
            {
    	
                //the user id is fetched and the if the user is not valid then he is redirected to the index page
    	
                String uid=(String)session.getAttribute("uid");
                if(uid==null||uid.equals(""))
                {
                        response.sendRedirect("index.jsp");
                }
    	
                //decreption of the user id is done
    	
                DesEncrypter encrypter = new DesEncrypter();
                        int uid1 = Integer.parseInt(encrypter.decrypt(uid));
                Connection con=DaoConnection.getcon(connectURL, DBuser, DBpass);
                Statement st=con.createStatement();
                ResultSet rs=st.executeQuery("SELECT * from USERS WHERE UID="+uid1);
                rs.next();
        
                // the new password is taken and the old password is replaced with the new one
    	
                String curpass = request.getParameter("curpass");
                String newpass = request.getParameter("newpass");
                String cnewpass = request.getParameter("cnewpass");
    	
                if(! newpass.equals(cnewpass)) {
                        session.setAttribute("message", "New passwords do not match.");
                        response.sendRedirect("changePassword.jsp");
                }else if (! curpass.equals(rs.getString("PASSWORD"))){
                        session.setAttribute("message", "Incorrect current password.");
                        response.sendRedirect("changePassword.jsp");
                }else {
    		
                // change password
                                String query = "UPDATE USERS SET PASSWORD = '"+newpass+"' WHERE UID = "+uid1;
                                PreparedStatement ps=con.prepareStatement(query);
                                ps.executeUpdate();
		
                                session.setAttribute("message", "Password changed succesfully.");
                                response.sendRedirect("home.jsp");
                }
                }catch(Exception e){
                        e.printStackTrace();
                        out.println(e.getMessage());
                }
        %>

    </body>
</html>
